package com.cgc.venus.server.core.aop;
import com.cgc.venus.server.core.base.BaseService;
import com.cgc.venus.server.core.utils.StringUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;

/**
 * Created by 业哥 on 2017/11/22.
 */
@Aspect
@Component
public class ControllerAop {
    private Logger logger = LoggerFactory.getLogger(ControllerAop.class);
    @Before("execution(public * com.cgc.venus.server.*.controller.*.*(..))")
    public void doBefore(JoinPoint joinPoint) {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            Object obj=joinPoint.getTarget();
            Field[] field =obj.getClass().getDeclaredFields();
            String token=request.getHeader("X-Token");
            String operObjectName="未知操作对象";
            String operObjectName0=request.getHeader("operObjectName");
            if(!StringUtil.isEmpty(operObjectName0)){
                operObjectName0=hexStringToString(operObjectName0);
                operObjectName=operObjectName0;
            }

            for (int i = 0; i < field.length; i++){
                try {
                    if (field[i].getGenericType().toString().indexOf("Service")!=-1){
                        field[i].setAccessible(true);
                        BaseService baseService = (BaseService) field[i].get(obj);
                        baseService.setOperObjectName(operObjectName);
                        baseService.setToken(token);
                    }
                }catch (Exception ex){
                    logger.warn(ex.getMessage());
                    //ex.printStackTrace();
                }
            }
        }catch (Exception ex){
            logger.warn(ex.getMessage());
        }
    }

    private String hexStringToString(String unicode) {
        StringBuffer string = new StringBuffer();
        String[] hex = unicode.split("\\\\u");
        for (int i = 1; i < hex.length; i++) {
            int data = Integer.parseInt(hex[i], 16);
            string.append((char) data);
        }
        return string.toString();
    }
}